package com.mind.customer.handler.tongwei;

import com.alibaba.fastjson2.JSON;
import com.mind.api.WebServiceClient;
import com.mind.api.webservice.ShareCallbackResponse;
import com.mind.common.utils.DateUtils;
import com.mind.common.utils.StringUtils;
import com.mind.customer.exception.CallbackException;
import com.mind.customer.mapper.AjReviewConfigMapper;
import com.mind.customer.mapper.AjTicketTaskMapper;
import com.mind.customer.utils.CateUtils;
import com.mind.system.domain.AjReviewConfig;
import com.mind.system.domain.AjTicketTask;
import com.mind.system.domain.SysConfig;
import com.mind.system.domain.vo.ShareCallBackVo;
import com.mind.system.mapper.SysConfigMapper;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Log4j2
@Component
public class CallbackHandler {
    @Value(value = "${shareCenter.webServiceUrl:}")
    private String webServiceUrl;

    @Value("${shareCenter.specialBusinessCateNames:}")
    private String specialBusinessCateName;

    @Value("${shareCenter.businessCateNameMaxCount:0}")
    private Integer businessCateNameMaxCount;
    @Resource
    private AjTicketTaskMapper ticketTaskMapper;
    @Resource
    private WebServiceClient webServiceClient;

    @Resource
    private AjReviewConfigMapper reviewConfigMapper;

    @Resource
    private SysConfigMapper sysConfigMapper;

    @Resource
    private CateUtils cateUtils;

    // TODO: 2024/9/29 0010 实现回调接口
    //   todo   重点开发这个 将稽核结果推送到对应的平台
    public void handle(Set<String> callbackResult, AjTicketTask task, String handleType, Map<Long, String> rulePassMapping) {
        Map<String, Integer> handleTypeMapping = new HashMap<String, Integer>() {{
            put("转人工", 1);
            put("退影像", 5);
            put("退回发起人", 2);
            put("自动通过", 6);
        }};
        String result = getResult(callbackResult, task, handleType, rulePassMapping);
        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique("zhishenceshizhuanyong");
        if (sysConfig != null && StringUtils.isNotEmpty(sysConfig.getConfigValue())) {
            result = sysConfig.getConfigValue();
        }
        String user = "BAIJY01";
        SysConfig userConfig = sysConfigMapper.checkConfigKeyUnique("auditUser");
        if (userConfig != null && StringUtils.isNotEmpty(userConfig.getConfigValue())) {
            user = userConfig.getConfigValue();
        }
        String finalResult = result;
        String finalUser = user;
        ShareCallBackVo shareCallBackVo = new ShareCallBackVo() {{
            setResult(finalResult);
            setComments("系统推送");
            setAuditUser(finalUser);
            setDate(DateUtils.getTime());
            setTicketId(task.getTicketId());
        }};
        Integer handleTypeInt = handleTypeMapping.get(result);
        ticketTaskMapper.updateTicketTask(new com.mind.system.domain.AjTicketTask() {{
            setId(task.getId());
            setHandleResult(handleTypeInt);
            setHandleType(finalResult.equals("转人工") ? 1 : 0);
            setCallbackParams(JSON.toJSONString(shareCallBackVo));
        }});
        try {
            ShareCallbackResponse response = webServiceClient.callWebService(webServiceUrl, shareCallBackVo);
            ticketTaskMapper.updateTicketTask(new com.mind.system.domain.AjTicketTask() {{
                setId(task.getId());
                setCallbackStatus(2);
                setHandelTime(new Date());
            }});
        } catch (Exception e) {
            throw new CallbackException(e.getMessage(), e.getCause());
        }
    }

    // 根据智审配置获取结果
    private String getResult(Set<String> callbackSet, AjTicketTask task, String handleType, Map<Long, String> rulePassMapping) {
        if (callbackSet == null) {
            callbackSet = new HashSet<>();
        }
        String result = "";
//        AjReviewConfig config = new AjReviewConfig();
//        if (StringUtils.isNotEmpty(task.getBusinessCate())) {
////            // 混报单特殊逻辑
////            if(StringUtils.isNotEmpty(specialBusinessCateName)){
////                List<String> specialBusinessCateNames = Arrays.asList(specialBusinessCateName.split(","));
////                int totalSize = specialBusinessCateNames.size();
////                List<String> businessCates = Arrays.asList(task.getBusinessCate().split(","));
////                specialBusinessCateNames.removeAll(businessCates);
////                if(totalSize-specialBusinessCateNames.size()  <= businessCateNameMaxCount){
////                    return "转人工";
////                }
////            }
//            config.setBusinessCateList(Arrays.asList(cateUtils.getSmallCate(task.getBusinessCate()).split(",")));
//        }
//
//        if (StringUtils.isNotEmpty(task.getTicketType())) {
//            config.setTicketTypeName(cateUtils.getTicketTypeByCode(task.getTicketType()));
//        }
        List<AjReviewConfig> reviewConfigs = reviewConfigMapper.selectAjReviewConfigList(new AjReviewConfig());
        log.info("tickTypeName: {}, businessCate: {},  handleType : {}, rulePassMapping: {}", cateUtils.getTicketTypeByCode(task.getTicketType()), task.getBusinessCate(), handleType, JSON.toJSONString(rulePassMapping));
        if (!CollectionUtils.isEmpty(reviewConfigs)) {
            List<String> chkResults = new ArrayList<>();
            for (AjReviewConfig reviewConfig : reviewConfigs) {
                // 如果智审配置中存在规则id，则根据规则id获取结果，有一条规则命中智审配置
//                if((StringUtils.isEmpty(reviewConfig.getTicketTypeName()) && StringUtils.isEmpty(reviewConfig.getBusinessCate())) || )
                log.info("reviewConfig: {}", JSON.toJSONString(reviewConfig));
                if (StringUtils.isNotNull(reviewConfig.getRuleDetailId()) && rulePassMapping.containsKey(reviewConfig.getRuleDetailId())) {
                    if (cateUtils.isMatched(reviewConfig, task, true)) {
                        if (rulePassMapping.get(reviewConfig.getRuleDetailId()).equals(reviewConfig.getChkStatus())) {
                            log.info("规则命中");
                            chkResults.add(reviewConfig.getChkResult());
                        }
                    }
                } else if (cateUtils.isMatched(reviewConfig, task, false) && handleType.equals(reviewConfig.getChkStatus())) {
                    log.info("其他命中");
                    chkResults.add(reviewConfig.getChkResult());
                }
            }
            // 没有规则命中智审
            if (!CollectionUtils.isEmpty(chkResults)) {
                callbackSet.addAll(chkResults);
            }
            // 智审命中自动通过，结果没有通过
//            if(result.equals("自动通过") && handleType.equals("2")){
//                result = "转人工";
//            }
        }
        log.info("智审结果:{}", JSON.toJSONString(callbackSet));
        result = getCallbackMethod(new ArrayList<>(callbackSet));
        if (StringUtils.isEmpty(result)) {
            result = "转人工";
        }
        return result;
    }

    private static String getCallbackMethod(List<String> chkResults) {
        String result = "转人工";
        if (!CollectionUtils.isEmpty(chkResults)) {
            if (chkResults.stream().anyMatch((s) -> s.equals("4"))) {
                result = "退回发起人";
            } else if (chkResults.stream().anyMatch((s) -> s.equals("3"))) {
                result = "退影像";
            } else if (chkResults.stream().anyMatch((s) -> s.equals("2"))) {
                result = "转人工";
            } else if (chkResults.stream().anyMatch((s) -> s.equals("1"))) {
                result = "自动通过";
            }
        }
        return result;
    }
}
